package com.fuful.servlet;

import com.fuful.domain.Page;
import com.fuful.domain.Product;
import com.fuful.service.ProductService;
import net.sf.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;
import java.io.OutputStream;
import java.io.PrintWriter;

public class FindProductAction extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        /**
         * 1.获得请求参数值
         * 2.调用业务逻辑
         * 3.获得结果
         * 4.根据结果判断是否需要共享对象(session/request)
         * 5.转发或重定向
         */
        int pn = Integer.parseInt(request.getParameter("pageNumber"));
        int ps = Integer.parseInt(request.getParameter("pageSize"));
        Page<Product> page = new Page<Product>();
        //1.pageNumber
        page.setPageNumber(pn);
        //2.pageSize
        page.setPageSize(ps);
        ProductService cs = new ProductService();
        //3.total
        int total =cs.count();
        page.setTotal(total);
        //4.rows
        List<Product> rows = cs.findByAll(pn,ps);
        page.setRows(rows);
        //把page写出到客户端
        response.setContentType("text/plain;charset=utf-8");
        PrintWriter out = response.getWriter();
        JSONObject jo = JSONObject.fromObject(page);
        out.print(jo);
        out.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req,resp);
    }
}

